const Fruit = cc.Class({
    name: 'FruitItem',
    properties: {
        id: 0,
        iconSF: cc.SpriteFrame,
    }
});

const JuiceItem = cc.Class({
    name: 'JuiceItem',
    properties: {
        particle: cc.SpriteFrame,
        circle: cc.SpriteFrame,
        slash: cc.SpriteFrame,
    }
});

var ATJSSDK = require("./AnyThinkAds/ATJSSDK"); 
var ATRewardedVideoJSSDK = require("./AnyThinkAds/ATRewardedVideoJSSDK");
cc.Class({
    extends: cc.Component,

    properties: {
        fruits: {
            default: [],
            type: Fruit   },

      juices: {
            default: [],
            type: JuiceItem
        },

        // 动态生成 找到批量处理预置元素的方案
        fruitPrefab: {
            default: null,
            type: cc.Prefab
        },

        juicePrefab: {
            default: null,
            type: cc.Prefab
        },

        // todo 可以实现一个audioManager
        boomAudio: {
            default: null,
            type: cc.AudioClip
        },
        knockAudio: {
            default: null,
            type: cc.AudioClip
        },
        waterAudio: {
            default: null,
            type: cc.AudioClip
        }
    },

    openVideo(){
    },

    onTouchStart(t){
        if(this.isOpen_remove==true){
            return;
        }
         //水果在下落中禁止移动
         if(this.isCreating==true){
            return;
        }
        const pos = t.getLocation()
        var size = cc.winSize;
        let {x, y} = pos
        x = x - size.width / 2
        this.currentFruit.position = cc.v2(x,this.currentFruit.position.y);
    },

    initAds(){
      
    },

    onLoad() {
        this.initAds();
        this.speed = 1;
        this.node.getChildByName("overBg").active = false;
        this.gmAuto = true;
        this.isOpen_remove = false;
        this.node.getChildByName("background").getChildByName("right").active = true;
        this.node.getChildByName("background").getChildByName("score").active = true;
        this.node.getChildByName("background").getChildByName("tip").active = false;
        this.initPhysics()
        this.clickGm();
        this.c_score = 0;
        this.refScore();
        this.isCreating = false
        this.fruitCount = 0;

        //设置line
        var size = cc.winSize;
        var y = size.height/2-300;
        this.node.getChildByName("background").getChildByName("line").position = cc.v2(0,y);
        this.node.getChildByName("background").getChildByName("line").active = false;

        // 监听点击事件 todo 是否能够注册全局事件
        var self = this;
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this)

        //根据触摸位置移动当前水果坐标
        this.node.on(cc.Node.EventType.TOUCH_MOVE, function(t) {
            if(self.isOpen_remove==true){
                return;
            }

            //水果在下落中禁止移动
            if(self.isCreating==true){
                return;
            }
            const pos = t.getLocation()
            var size = cc.winSize;
            let {x, y} = pos
            x = x - size.width / 2
            this.currentFruit.position = cc.v2(x,this.currentFruit.position.y);
            self.currentFruit.getChildByName("tuowei").active = false;
        }, this)

        this.node.on(cc.Node.EventType.TOUCH_END, function(t) {
            //参数：移除某个道具，正常流程掉落
            if(self.isOpen_remove==true){
                var size = cc.winSize;
                var p = cc.v2(t.getLocation().x-size.width/2,t.getLocation().y-size.height/2)
                self.findContains(p);
            }else{
                // self.currentFruit.getChildByName("tuowei").active = true;
                self.currentFruit.getChildByName("tuowei").active = false;
                self.onTouchEnd(t);
            }
        }, this),

        this.node.on(cc.Node.EventType.TOUCH_CANCEL, function(t) {
            //参数：移除某个道具，正常流程掉落
            if(self.isOpen_remove==true){
                var size = cc.winSize;
                var p = cc.v2(t.getLocation().x-size.width/2,t.getLocation().y-size.height/2)
                self.findContains(p);
            }else{
                // self.currentFruit.getChildByName("tuowei").active = true;
                self.currentFruit.getChildByName("tuowei").active = false;
                self.onTouchEnd(t);
            }
        }, this),

        this.initOneFruit()
    },

    clickGm(){
        this.gmAuto = !this.gmAuto;
        if(this.gmAuto==true){
            this.node.getChildByName("background").getChildByName("auto").getChildByName("v").getComponent(cc.Label).string = "已开启持续生成";
        }else{
            this.node.getChildByName("background").getChildByName("auto").getChildByName("v").getComponent(cc.Label).string = "已关闭持续生成";
        }
    },

    clickSpeed(){
        if(this.speed == 1){
            this.speed = 0.8
        }else if(this.speed == 0.8){
            this.speed = 0.5
        }else if(this.speed == 0.5){
            this.speed = 0.2
        }else {
            this.speed = 1
        }
        this.node.getChildByName("background").getChildByName("create").getChildByName("v").getComponent(cc.Label).string = "生成速度："+this.speed;

    
    },

    findContains(p){
        var f = this.node.getChildByName("fruits");
        var isH = false;
        for(var i = 0;i<f.childrenCount;i++){
            if(i<=f.childrenCount-1){
                var node_box = f.getChildren()[i].getBoundingBox();
                if(node_box.contains(p)==true){
                    if(isH==false && f.getChildren()[i].uuid!=this.currentFruit.uuid){
                        f.getChildren()[i].destroy();
                        cc.audioEngine.play(this.boomAudio, false, 1);
                        cc.audioEngine.play(this.waterAudio, false, 1);
                        // 展示动画
                        let juice = cc.instantiate(this.juicePrefab);
                        this.node.addChild(juice);
                        const {x, y} = f.getChildren()[i]
                        const config = this.juices[0]
                        const instance = juice.getComponent('Juice')
                        instance.init(config)
                        instance.showJuice(cc.v2({x, y}), f.getChildren()[i].width)
                        isH = true;
                    }
                }
            }
        }

        if(isH==true){
            this.isCreating = false;
            this.isOpen_remove = false;
            this.node.getChildByName("background").getChildByName("right").active = true;
            this.node.getChildByName("background").getChildByName("score").active = true;
            this.node.getChildByName("background").getChildByName("tip").active = false;
     
    



          
        }
    },

    refScore(){
        this.node.getChildByName("background").getChildByName("score").getComponent(cc.Label).string = this.c_score;
    },

    // 开启物理引擎和碰撞检测
    initPhysics() {
        // 物理引擎
        const instance = cc.director.getPhysicsManager()
        instance.enabled = true
        // instance.debugDrawFlags = 4
        instance.gravity = cc.v2(0, -960);

        // 碰撞检测
        const collisionManager = cc.director.getCollisionManager();
        collisionManager.enabled = true

        // 设置四周的碰撞区域
        let width = this.node.width;
        let height = this.node.height;

        let node = new cc.Node();

        let body = node.addComponent(cc.RigidBody);
        body.type = cc.RigidBodyType.Static;

        const _addBound = (node, x, y, width, height) => {
            let collider = node.addComponent(cc.PhysicsBoxCollider);
            collider.offset.x = x;
            collider.offset.y = y;
            collider.size.width = width;
            collider.size.height = height+300;
        }

        _addBound(node, 0, -height / 2, width, 1);
        _addBound(node, 0, height / 2, width, 1);
        _addBound(node, -width / 2, 0, 1, height);
        _addBound(node, width / 2, 0, 1, height);

        node.parent = this.node;
    },

    initOneFruit(id = 1) {
        this.fruitCount++;
        var size = cc.winSize;
        var y = size.height/2-200;
        this.currentFruit = this.createFruitOnPos(0, y, id)

        this.findPos();
    },

    // 监听屏幕点击
    onTouchEnd(e) {
        if (this.isCreating) return
        this.isCreating = true
        const {width, height} = this.node


        const fruit = this.currentFruit

        const pos = e.getLocation()
        let {x, y} = pos
        x = x - width / 2
        // y = y - height / 2



        if(this.isOpen_remove==true){
            return;
        }

        //        const action = cc.sequence(cc.moveBy(0.3, cc.v2(x, fruit.position.y)).easing(cc.easeCubicActionIn()), cc.callFunc(() => {
        // 开启物理效果
        this.startFruitPhysics(fruit)


        var self = this;
        // 1s后重新生成一个
        this.scheduleOnce(() => {
            self.currentFruit.getChildByName("tuowei").active = false;
            const nextId = this.getNextFruitId()
            this.initOneFruit(nextId)
            this.isCreating = false
            if(self.gmAuto == true){
                this.onTouchEnd(e);
            }
        }, self.speed)



        // const action = cc.sequence(cc.callFunc(() => {
           
        // }))
        // fruit.runAction(action)
    },

    // 获取下一个水果的id
    getNextFruitId() {
        if (this.fruitCount < 3) {
            return 1
        } else if (this.fruitCount === 3) {
            return 2
        } else {
            // 随机返回前5个
            return Math.floor(Math.random() * 5) + 1
        }
    },

    //检查线
    findPos(){
        var isDie = false;
        this.node.getChildByName("background").getChildByName("line").active = false;
        console.log(this.currentFruit.position);

        var f = this.node.getChildByName("fruits");
        for(var i = 0;i<f.childrenCount;i++){
            if(f.getChildren()[i].uuid!=this.currentFruit.uuid){
                if(f.getChildren()[i].position.y>100){
                    this.node.getChildByName("background").getChildByName("line").active = true;
                    var size = cc.winSize;
                    var y = size.height/2-300;
                    if(f.getChildren()[i].position.y+f.getChildren()[i].width/2>y){
                        //结束
                        isDie = true;
                    }
                }
            }
        }
        if(isDie==true){
           //结算面版
           var overBg = this.node.getChildByName("overBg");
           overBg.active = true;
           overBg.getChildByName("curScore").getComponent(cc.Label).string = this.c_score;
           var maxScore_daxigua = cc.sys.localStorage.getItem('maxScore_daxigua');
           if(maxScore_daxigua==null || maxScore_daxigua==undefined){
               maxScore_daxigua = 0;
           }else{
               maxScore_daxigua = parseInt(maxScore_daxigua);
           }
           if(maxScore_daxigua<this.c_score){
               maxScore_daxigua = this.c_score;
           }
           cc.sys.localStorage.setItem('maxScore_daxigua', maxScore_daxigua);
           overBg.getChildByName("maxScore").getComponent(cc.Label).string = maxScore_daxigua;
        }
        return isDie;
    },


    // 创建一个水果
    createOneFruit(num) {
        let fruit = cc.instantiate(this.fruitPrefab);
        const config = this.fruits[num - 1]

        fruit.getComponent('Fruit').init({
            id: config.id,
            iconSF: config.iconSF
        });


        fruit.getComponent(cc.RigidBody).type = cc.RigidBodyType.Static
        fruit.getComponent(cc.PhysicsCircleCollider).radius = 0

        this.node.getChildByName("fruits").insertChild(fruit, this.node.getChildByName("fruits").childrenCount);
        // this.node.getChildByName("fruits").addChild(fruit);
        fruit.scale = 0.6

        // 有Fruit组件传入
        fruit.on('sameContact', this.onSameFruitContact.bind(this))

        return fruit
    },

    startFruitPhysics(fruit) {
        fruit.getComponent(cc.RigidBody).type = cc.RigidBodyType.Dynamic
        const physicsCircleCollider = fruit.getComponent(cc.PhysicsCircleCollider)
        physicsCircleCollider.radius = fruit.height / 2
        physicsCircleCollider.apply()
    },

    // 在指定位置生成水果
    createFruitOnPos(x, y, type = 1) {
        const fruit = this.createOneFruit(type)
        fruit.setPosition(cc.v2(x, y));
        return fruit
    },
    // 两个水果碰撞
    onSameFruitContact({self, other}) {
        other.node.off('sameContact') // 两个node都会触发，todo 看看有没有其他方法只展示一次的

        const id = other.getComponent('Fruit').id
        // todo 可以使用对象池回收
        self.node.removeFromParent(false)
        other.node.removeFromParent(false)

        const {x, y} = other.node

        this.createFruitJuice(id, cc.v2({x, y}), other.node.width)
        console.log("合成了"+id,"分数+"+id+1,"之前分数"+this.c_score);
        this.c_score += parseInt(id) + 1;
        this.refScore();

        if(id==10){
            this.playAnim();
        }

        const nextId = id + 1
        if (nextId <= 11) {
            const newFruit = this.createFruitOnPos(x, y, nextId)

            this.startFruitPhysics(newFruit)
            // 展示动画 todo 动画效果需要调整
            newFruit.scale = 0
            cc.tween(newFruit).to(.5, {
                scale: 0.6
            }, {
                easing: "backOut"
            }).start()
        } else {
            // todo 合成两个西瓜
            console.log(' todo 合成两个西瓜 还没有实现哦~ ')
        }
    },

    playAnim(){
        var xigua = this.node.getChildByName("xigua");
        xigua.active = true;
        xigua.getChildByName("con").scale = 0.1;

        var self = this;
        var callFunc = cc.callFunc(
            function(){
                xigua.active = false;
            }
        )
        var action1 = cc.scaleTo(2, 1);
        var action2 = cc.scaleTo(2, 1);
        var se = cc.sequence(action1,action2, callFunc);
        xigua.getChildByName("con").runAction(se);

    },

    // 合并时的动画效果
    createFruitJuice(id, pos, n) {
        // 播放合并的声音
        cc.audioEngine.play(this.boomAudio, false, 1);
        cc.audioEngine.play(this.waterAudio, false, 1);

        // 展示动画
        let juice = cc.instantiate(this.juicePrefab);
        this.node.addChild(juice);

        const config = this.juices[id - 1]
        const instance = juice.getComponent('Juice')
        instance.init(config)
        instance.showJuice(pos, n)
    },

    //3个道具 
    //随机打乱水果位置
    daojuAction1(){
        //查询所有水果，随机位置下落
        var f = this.node.getChildByName("fruits");
        var nodes = [];
        for(var i = 0;i<f.childrenCount;i++){
            f.getChildren()[i].active = false;
            if(f.getChildren()[i].uuid!=this.currentFruit.uuid){
                nodes.push(f.getChildren()[i]);
            }
        }
        this.changeIndex(nodes);
    },

    changeIndex(nodes){
        var self = this;
        var t = nodes.length;
        this.schedule(function(){
            t--;
            if(t<0){
                self.currentFruit.active = true;
                self.isCreating = false;
                self.unscheduleAllCallbacks();
            }else{
                nodes[t].active = true;
                var size = cc.winSize;
                var y = size.height/2-200;
                var x = self.random(-size.width/2,size.width/2);
                nodes[t].position = cc.v2(x,y)
            }
        },0.3);
    },

    sortArr(myarr){
        var i = myarr.length;
        while(i){
            var j = Math.floor(Math.random()*i--);
            myarr[i] = myarr[j];
            myarr[j] = myarr[i];
        }
    },
       
    random(lower,upper){
        return Math.floor(Math.random()*(upper-lower+1))+lower;
    },

    daojuAction2(){
        this.isOpen_remove = true;
        this.node.getChildByName("background").getChildByName("right").active = false;
        this.node.getChildByName("background").getChildByName("score").active = false;
        this.node.getChildByName("background").getChildByName("tip").active = true;
    },

    cancelDaoju2(){
        this.isCreating = false;
        this.isOpen_remove = false;
        this.node.getChildByName("background").getChildByName("right").active = true;
        this.node.getChildByName("background").getChildByName("score").active = true;
        this.node.getChildByName("background").getChildByName("tip").active = false;
    },

    daojuAction3(){
        this.currentFruit.getChildByName("wanneng").active = true;
        this.currentFruit.getComponent("Fruit").resetSprite();
    },

    //over
    resetAction(){
        cc.director.loadScene("game",function(){
        })
    },
    goonAction(){
        this.node.getChildByName("overBg").active = false;
        this.node.getChildByName("fruits").removeAllChildren();
        const nextId = this.getNextFruitId()
        this.initOneFruit(nextId)
        this.isCreating = false
    },



});